/*
 * This file is part of TradeHelper library.
 *
 * TradeHelper library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TradeHelper library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TradeHelper library.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.rag.managers;

import com.alee.managers.settings.SettingsManager;
import com.alee.utils.CollectionUtils;
import com.alee.utils.collection.ValuesTable;
import com.rag.core.SingleTopicData;
import com.rag.managers.favorites.FavoritesListener;

import java.util.ArrayList;
import java.util.List;

/**
 * User: mgarin Date: 07.06.12 Time: 16:02
 */

public class FavoritesManager
{
    private static String favoritesFile = "Favorites.xml";

    private static final Object listenersLock = new Object ();
    private static List<FavoritesListener> listeners = new ArrayList<FavoritesListener> ();

    private static ValuesTable<String, SingleTopicData> favorites = null;

    private static boolean initialized = false;

    public static void initializeManager ()
    {
        if ( !initialized )
        {
            initialized = true;

            // Загружаем список избранных топиков
            loadFavorites ();
        }
    }

    public static List<SingleTopicData> getFavorites ()
    {
        return favorites.getValues ();
    }

    public static void updateFavoriteTopics ( List<SingleTopicData> topics )
    {
        // Обновляем данные избранных топиков
        List<SingleTopicData> updated = new ArrayList<SingleTopicData> ();
        for ( SingleTopicData update : topics )
        {
            SingleTopicData toUpdate = favorites.get ( update.getId () );
            if ( toUpdate != null )
            {
                favorites.put ( toUpdate.getId (), update );
                updated.add ( update );
            }
        }

        // Сохраняем новый список
        saveFavorites ();

        // Оповещаем слушателей об обновлении
        fireFavoriteTopicsUpdated ( updated );
    }

    public static boolean isFavorite ( SingleTopicData topicData )
    {
        return favorites.get ( topicData.getId () ) != null;
    }

    public static boolean addFavoriteTopic ( SingleTopicData topicData )
    {
        // Игнорируем нулевой топик
        if ( topicData == null )
        {
            return false;
        }

        SingleTopicData contained = favorites.get ( topicData.getId () );
        if ( contained == null )
        {
            // Добавляем топик в список избранных
            favorites.put ( topicData.getId (), topicData );

            // Сохраняем новый список
            saveFavorites ();

            // Оповещаем слушателей об удалении
            fireFavoriteTopicAdded ( topicData );
        }

        return true;
    }

    public static void removeFavoriteTopic ( SingleTopicData topicData )
    {
        // Игнорируем нулевой топик
        if ( topicData == null )
        {
            return;
        }

        SingleTopicData toRemove = favorites.get ( topicData.getId () );
        if ( toRemove != null )
        {
            // Удаляем топик из списка избранных
            favorites.remove ( toRemove.getId () );

            // Сохраняем новый список
            saveFavorites ();

            // Оповещаем слушателей об удалении
            fireFavoriteTopicRemoved ( toRemove );
        }
    }

    public static void addFavoritesListener ( FavoritesListener listener )
    {
        synchronized ( listenersLock )
        {
            listeners.add ( listener );
        }
    }

    public static void removeFavoritesListener ( FavoritesListener listener )
    {
        synchronized ( listenersLock )
        {
            listeners.remove ( listener );
        }
    }

    private static void fireFavoriteTopicAdded ( SingleTopicData topicData )
    {
        for ( FavoritesListener listener : CollectionUtils.clone ( listeners ) )
        {
            listener.favoriteTopicAdded ( topicData );
        }
    }

    private static void fireFavoriteTopicsUpdated ( List<SingleTopicData> topicData )
    {
        for ( FavoritesListener listener : CollectionUtils.clone ( listeners ) )
        {
            listener.favoriteTopicsUpdated ( topicData );
        }
    }

    private static void fireFavoriteTopicRemoved ( SingleTopicData topicData )
    {
        for ( FavoritesListener listener : CollectionUtils.clone ( listeners ) )
        {
            listener.favoriteTopicRemoved ( topicData );
        }
    }

    private static void loadFavorites ()
    {
        if ( favorites == null )
        {
            favorites = SettingsManager
                    .getSettings ( favoritesFile, new ValuesTable<String, SingleTopicData> () );
        }
    }

    private static void saveFavorites ()
    {
        SettingsManager.setSettings ( favoritesFile, favorites );
    }
}